import { defineStore } from "pinia"

import * as api from "@/api/permission"

import recursionRoute from "@/utils/recursionRoute"

import dynamicRoute from "@/router/dynamicRoute"

import staticRoute  from "@/router/staticRoute"

import router from "@/router/index"

//生成菜单的思路(权限菜单)

//1.本地配置一套完整的路由

//2.发起请求,请求用户的菜单数据

//3.用请求的菜单数据和用户本地的路由数据进行对比

//4.通过addRoute方法进行动态路由的添加

//5.菜单数据注入到elment菜单组件中,并且递归生成菜单

export default defineStore('menu', {
    state() {
        return {
            menulist: [],
            userRoutes: [], //用户的路由
            breadcrumb:[]//面包屑数据
        }
    },
    actions: {
        //拉取用户后台对应的菜单
        async FETCH_MENULIST() {
            try {
                let res = await api.getMenulistApi();
                let menulist = res.data.menuList;
                //使用递归函数对比出用户的路由

                let userRoute = recursionRoute(dynamicRoute, menulist)

                //赋值给state
                this.userRoutes = [...userRoute];
                this.menulist = [...userRoute]
                // console.log(this.userRoutes)
                staticRoute.children = [...this.userRoutes,...staticRoute.children]

                // console.log(staticRoute)
                //动态添加路由 router.addRoute(符合路由配置的一个对象)

                router.addRoute(staticRoute)

                return Promise.resolve('逻辑处理完毕')
              
            } catch (e) {
                console.log(e)
            }
        }
    }
})